package application.Service;

import application.Pojo.Failure;
import application.Pojo.Success;
import application.utils.Utils;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

/**
 * @Auther: Ohto_Ai
 * @Date: 2022/2/23 - 02 - 23 - 10:07
 * @Description: Service
 * @version: 1.0
 */
@WebServlet("/sendreturnapplication")
public class SendReturnApplication extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");


        //用户名（名字+学号）
        String username = null;

        //借书的日期
        String borrow_date = null;

        //书籍id
        String bookid = null ;

        //还书日期
        String return_date = null;

        //email
        String email = null;
        
        //借书申请数据库的连接、处理、结果对象
        Connection borrowApply = null;
        Statement bstmt = null;
        ResultSet brs = null;

        //还书申请数据库的连接、处理、结果对象
        Connection returnApply = null;
        PreparedStatement rstmt = null;
        ResultSet rrs = null;
        
        try {

            //得到request中的JSON信息、
            Utils utils = new Utils();
            JSONObject jsonObject = utils.getJSONObject(req);
            username = jsonObject.getString("username");
            bookid = jsonObject.getString("bookid");

            //连接借书申请数据库
            borrowApply = utils.JDBCConection("com.mysql.jdbc.Driver","jdbc:mysql://127.0.0.1:3306/apply","root","123456");

            //设置事务不自动提交
            borrowApply.setAutoCommit(false);

            //创建sql语句
            StringBuilder sbusql = new StringBuilder("SELECT username,bookid,borrow_date,return_date,email FROM borrowapply WHERE username = \"");

            sbusql.append(username);
            sbusql.append("\" AND bookid = \"");
            sbusql.append(bookid);
            sbusql.append("\";");
            String bsql = sbusql.toString();

            //获区借书申请数据库结果
            bstmt = borrowApply.createStatement();
            brs = bstmt.executeQuery(bsql);


            //获取用户数据库中的email和username
            while(brs.next()){

                username = brs.getString("username");
                bookid = brs.getString("bookid");
                borrow_date = brs.getString("borrow_date");
                return_date = brs.getString("return_date");
                email = brs.getString("email");
            }
            System.out.println(username+bookid+borrow_date+return_date+email);




            //连接还书申请数据库
            returnApply = utils.JDBCConection("com.mysql.jdbc.Driver","jdbc:mysql://127.0.0.1:3306/apply","root","123456");

            //设置事务不自动提交
            returnApply.setAutoCommit(false);

            //sql
            String rsql = "INSERT INTO returnapply(username,bookid,borrow_date,return_date,email,status) VALUES(?,?,?,?,?,?)";

            //录入还书申请数据库
            rstmt = returnApply.prepareStatement(rsql);
            rstmt.setString(1,username);
            rstmt.setString(2,bookid);
            rstmt.setString(3,borrow_date);
            rstmt.setString(4,return_date);
            rstmt.setString(5,email);
            rstmt.setString(6,"申请中");

            rstmt.executeUpdate();

            //返回包含正确访问码和信息的JSON字符串
            Success success = new Success();
            success.setCode("200");
            success.setMessage("申请成功，请等待管理员审批");

            String json = JSONObject.toJSONString(success);

            //将json对象转化为字符串在终端输出
            System.out.print(json);

            //把json数据返回给浏览器：
            resp.getWriter().write(json);

            borrowApply.commit();
            returnApply.commit();

        } catch (Exception e) {

            e.printStackTrace();
            //捕捉异常并且 返回包含错误码信息对象的JSON字符串
            Failure failure = new Failure();
            failure.setCode("-1");
            failure.setMessage("申请失败，请确认用户名和书籍编号的正确填写！");

            String json = JSONObject.toJSONString(failure);

            //将json对象转化为字符串在终端输出
            System.out.print(json);

            //把json数据返回给浏览器：
            resp.getWriter().write(json);

            //出现异常事务回滚
            try {
                borrowApply.rollback();
                returnApply.rollback();

            } catch (SQLException ex) {
                ex.printStackTrace();
                //捕捉异常并且 返回包含错误码信息对象的JSON字符串
                Failure rollbackfailure = new Failure();
                failure.setCode(String.valueOf(ex.getErrorCode()));
                failure.setMessage(ex.getMessage());

                String rollbackjson = JSONObject.toJSONString(failure);

                //将json对象转化为字符串在终端输出
                System.out.print(rollbackjson);

                //把json数据返回给浏览器：
                resp.getWriter().write(rollbackjson);
            }
        }finally {

            try {
                if ( brs != null){
                    brs.close();
                }
                if (bstmt != null){
                    bstmt.close();
                }
                if (borrowApply != null){
                    borrowApply.close();
                }

                if ( rrs != null){
                    rrs.close();
                }
                if (rstmt != null){
                    rstmt.close();
                }
                if (returnApply != null){
                    returnApply.close();
                }

            } catch (SQLException e) {

                e.printStackTrace();
                //捕捉异常并且 返回包含错误码信息对象的JSON字符串
                Failure failure = new Failure();
                failure.setCode(String.valueOf(e.getErrorCode()));
                failure.setMessage(e.getMessage());

                String json = JSONObject.toJSONString(failure);

                //将json对象转化为字符串在终端输出
                System.out.print(json);

                //把json数据返回给浏览器：
                resp.getWriter().write(json);

                //出现异常事务回滚
                try {
                    borrowApply.rollback();
                    returnApply.rollback();

                } catch (SQLException ex) {

                    ex.printStackTrace();
                    //捕捉异常并且 返回包含错误码信息对象的JSON字符串
                    Failure rollbackfailure = new Failure();
                    failure.setCode(String.valueOf(ex.getErrorCode()));
                    failure.setMessage(ex.getMessage());

                    String rollbackjson = JSONObject.toJSONString(failure);

                    //将json对象转化为字符串在终端输出
                    System.out.print(rollbackjson);

                    //把json数据返回给浏览器：
                    resp.getWriter().write(rollbackjson);
                }
            }
        }
    }
}


